import { Channel } from '@/types/data'
import { HomeAction } from '@/types/store'
import { sortBy } from 'lodash'
type HomeState = {
  userChannel: Channel[]
  restChannel: Channel[]
  channelActiveKey: string
}
const initialState: HomeState = {
  userChannel: [],
  restChannel: [],
  channelActiveKey: '0',
}

export const home = (state = initialState, action: HomeAction) => {
  switch (action.type) {
    // 我的频道
    case 'home/getUserChannel':
      return {
        ...state,
        userChannel: action.payload,
      }
    // 可选频道
    case 'home/getAllChannel':
      return {
        ...state,
        restChannel: action.payload,
      }
    // 高亮切换
    case 'home/changeTab':
      return {
        ...state,
        channelActiveKey: action.payload,
      }
    // 删除我的
    case 'home/delChannel':
      return {
        ...state,
        // 删除当前频道
        userChannel: state.userChannel.filter(
          (item) => item.id !== action.payload.id
        ),
        // 将被删除频道添加到推荐频道中，并且根据 id 进行排序
        restChannel: sortBy([...state.restChannel, action.payload], 'id'),
      }
    // 新增我的
    case 'home/addChannel':
      return {
        ...state,
        // 新增我的频道
        userChannel: [...state.userChannel, action.payload],
        // 从推荐中删除
        restChannel: state.restChannel.filter(
          (item) => item.id !== action.payload.id
        ),
      }
    default:
      return state
  }
}
